﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;

namespace GenericValidation.Validators
{
    /// <summary>
    /// Defines String members Lenght validation, with the options to validate minimum, maximum and between interval string lenght.
    /// </summary>
    /// <typeparam name="TEntity"></typeparam>
    public class StringLengthValidator<T> : MemberValidator<T, string>
        where T:class
    {

        public StringLengthValidator(ValidationMember<T, string> member, int? minLength, int? maxLength)
            : base(member)
        {
            var field = member.MemberExpression.Compile();
            //is greater than
            if (minLength != null)
            {
                this.Evaluate = (p) => field(p) == null || minLength < field(p).Length;
                this.Message(Templates.IsLengthGreater, p => member.MemberName, p => minLength, p => (field(p) ?? string.Empty).Length);
            }

            //is lower than
            if (maxLength != null)
            {
                if (this.Evaluate != null)
                {
                    this.Evaluate = (p) => field(p) == null || (
                        minLength < field(p).Length
                        && field(p) != null && field(p).Length < maxLength);
                }
                else
                {
                    this.Evaluate =  (p) => field(p) == null || field(p).Length < maxLength;
                }

                this.Message(Templates.IsLengthLower, p => member.MemberName, p => maxLength, p => (field(p) ?? string.Empty).Length);
            }

        }
    }
}
